package com.example.elderlycare.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.elderlycare.dao.entity.CheckRecord;
import com.example.elderlycare.dao.entity.Common;
import com.example.elderlycare.dao.mapper.CheckRecordMapper;
import com.example.elderlycare.dao.mapper.CommonMapper;
import com.example.elderlycare.service.CheckRecordService;
import com.example.elderlycare.service.entity.CheckRecordItem;
import com.example.elderlycare.service.entity.CheckRecordListResponseBody;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CheckRecordServiceImpl extends ServiceImpl<CheckRecordMapper, CheckRecord>
        implements CheckRecordService {
    @Resource
    CheckRecordMapper checkRecordMapper;

    @Resource
    CommonMapper commonMapper;

    @Override
    public CheckRecordListResponseBody queryCheckRecord(Map<String, Object> params) {
        QueryWrapper<Common> queryWrapper = new QueryWrapper<>();
        /* type = 3、11 分别对应证件类型、入住状态的字典 */
        queryWrapper.eq("type", 3).or().eq("type", 11);
        List<Common> commonList = commonMapper.selectList(queryWrapper);
        Map<Integer, Common> commonMap = new HashMap<>();
        commonList.forEach((item) -> commonMap.put(item.getId(), item));


        CheckRecordListResponseBody checkRecordListResponseBody = new CheckRecordListResponseBody();
        int total = checkRecordMapper.getCheckRecordsCount(params);
        checkRecordListResponseBody.setTotal(total);
        List<CheckRecord> checkRecords = checkRecordMapper.queryCheckRecords(params);
        List<CheckRecordItem> items = new ArrayList<>();
        for (CheckRecord checkRecord : checkRecords) {
            CheckRecordItem item = CheckRecordItem.builder()
                    .id(checkRecord.getId())
                    .elderId(checkRecord.getElderId())
                    .elderName(checkRecord.getElder().getName())
                    .certificate(commonMap.get(checkRecord.getElder().getCertificateId()).getName())
                    .sex(checkRecord.getElder().getSex())
                    .age(new Date().getYear() - checkRecord.getElder().getBirthday().getYear())
                    .number(checkRecord.getElder().getNumber())
                    .nursingHomeId(checkRecord.getNurseId())
                    .nursingHomeName(checkRecord.getNursingHome().getName())
                    .startTime(checkRecord.getStartTime())
                    .inStatus(commonMap.get(checkRecord.getInStatusId()).getName())
                    .bedNumber(checkRecord.getBedNumber())
                    .build();
            items.add(item);
        }
        checkRecordListResponseBody.setCheckRecordItemList(items);
        return checkRecordListResponseBody;
    }
}
